using System;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using NHibernate;

namespace L2NH.Infrastructure.DataAccess
{
   public class UnitOfWork
   {
      static UnitOfWork()
      {
         _sessionFactory = Fluently.Configure()
            .Database(MsSqlConfiguration
                         .MsSql2005
                         .ConnectionString(App.Settings.ConnectionString)
                         .ShowSql())
            .Mappings(mapping => mapping.FluentMappings.AddFromAssemblyOf<NHRepository>())
            .BuildSessionFactory();
      }

      private static readonly ISessionFactory _sessionFactory;

      public static ISession CurrentSession { get; private set; }

      public static void Begin()
      {
         if (CurrentSession != null)
            throw new ApplicationException("Unit of Work already started");

         CurrentSession = _sessionFactory.OpenSession();
         CurrentSession.FlushMode = FlushMode.Commit;
         CurrentSession.BeginTransaction();
      }

      public static void End()
      {
         if (CurrentSession == null) return;

         CurrentSession.Transaction.Rollback();
         CurrentSession.Dispose();
         CurrentSession = null;
      }

      public static void CloseSessionFactory()
      {
         _sessionFactory.Dispose();
      }

   }
}